package com.byxy.dao.impl;

import com.byxy.dao.AdminRuleDao;
import com.byxy.model.AdminRule;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class AdminRuleDaoImplBackup implements AdminRuleDao {
    @Autowired
    private HibernateTemplate hibernateTemplate;

    @Override
    public void save(AdminRule adminRule) {
        hibernateTemplate.save(adminRule);
    }

    @Override
    public void delete(Integer id) {
        AdminRule adminRule = hibernateTemplate.get(AdminRule.class, id);
        hibernateTemplate.delete(adminRule);
    }

    @Override
    public void update(AdminRule adminRule) {
        hibernateTemplate.update(adminRule);
    }

    @Override
    public AdminRule get(Integer id) {
        return hibernateTemplate.get(AdminRule.class, id);
    }

    @Override
    public List<AdminRule> listPage(Integer pageNum, Integer pageSize, String search) {
        //language=HQL
        String hql = "FROM AdminRule WHERE title LIKE :search";
        List<AdminRule> list = hibernateTemplate.execute(new HibernateCallback<List<AdminRule>>() {
            @Override
            public List<AdminRule> doInHibernate(Session session) throws HibernateException {
                Query query = session.createQuery(hql);
                query.setString("search", "%".concat(search).concat("%"));
                if (pageNum > 0 && pageSize > 0) {
                    query.setFirstResult((pageNum - 1) * pageSize);
                    query.setMaxResults(pageSize);
                }
                return query.list();
            }
        });
        return list;
    }

    @Override
    public Integer count(String search) {
        //language=HQL
        String hql = "SELECT COUNT(*) FROM AdminRule WHERE title LIKE :search";
        String paramName = "search";
        String value = "%".concat(search).concat("%");
        List list = hibernateTemplate.findByNamedParam(hql, paramName, value);
        return (int) ((long) (list.get(0)));
    }

    /*
        只有level为1或者2才会是父级菜单
     */
    @Override
    public List<AdminRule> listPid() {
        //language=HQL
        String hql = "FROM AdminRule WHERE level IN (1, 2)";
        return (List<AdminRule>) hibernateTemplate.find(hql);
    }
}
